layui.define(['index', 'form', 'layedit', 'laydate', 'formSelects', 'upload'], function (exports) {
    let $ = layui.$;
    let form = layui.form;
    let layer = layui.layer;
    let laydate = layui.laydate;
    let upload = layui.upload;
    let formSelects = layui.formSelects;

    let pushNoticeApp = json.pushNoticeApp;
    let pushNoticeAppVo = json.pushNoticeAppVo;
    let id = pushNoticeApp.id;
    let defaultMaxNum = "99999";
    let defaultMaxTime = "9999-12-31 23:59:59";
    let defaultMinValue = "";

    zmnLayUtil.layFormVerify(form, {});

    initLayDataByEmeId("beginTime");
    initLayDataByEmeId("endTime");
    // zmnUploadUtil.uploaderImage($, upload, "picUrlView", "picUrl", '/mast/master/uploaderImageUnpressed.action?timestamp=' + new Date().getTime() + '&elemId=picUrlView');
    zmnUploadUtil.uploaderImage($, upload, "picUrlView", "picUrl", '/push/noticeApp/ajax/uploaderImage.action?timestamp=' + new Date().getTime() + '&elemId=picUrlView');

    setPicType(pushNoticeApp.putType);
    setBeginTimeType(pushNoticeApp.putType);
    if (zmnUtil.isNull(id)) {
        // 认为是新增,默认选中 首页弹窗
        let defaultPageData = {
            putType: "2",
            isJump: "1",
            mustRead: "1"
        };
        form.val("zmn-form", defaultPageData);
        hideByEmeId("picLinkTitle", "picLink");
        homepage();
    } else {
        // 修改
        pushNoticeApp.putType = pushNoticeApp.putType.toString();

        if (zmnUtil.isNull(pushNoticeApp.picLink) || pushNoticeApp.picLink === '') {
            pushNoticeApp.isJump = "1";
        } else {
            pushNoticeApp.isJump = "2";
        }

        if (pushNoticeApp.putType === "3") {
            pushMsg();
        } else if (pushNoticeApp.putType === "2") {
            homepage();
        } else if (pushNoticeApp.putType === "1") {
            loadingPage();
        } else {
            return false;
        }
        pushNoticeApp.beginTime = zmnUtil.createTime(pushNoticeApp.beginTime);
        pushNoticeApp.endTime = zmnUtil.createTime(pushNoticeApp.endTime);

        pushNoticeApp.showTime = pushNoticeApp.showTime.toString();
        pushNoticeApp.putType = pushNoticeApp.putType.toString();
        pushNoticeApp.mustRead = pushNoticeApp.mustRead.toString();
        // 回显图片
        zmnUploadUtil.reLoadImage($, "picUrlView", pushNoticeApp.picUrl, "picUrl");
        // 检查是否长期生效
        setEndTime(pushNoticeApp.endTime);
        // 检查用户显示总次数为不限
        setIsUserShowTimesAll(pushNoticeApp.userShowTimesAll);
        // 检查用户每天显示次数为不限
        setIsUserShowTimesDay(pushNoticeApp.userShowTimesDay);
        // 回显投放app
        setCheckboxData(pushNoticeAppVo.putAppList);
        // 回显投放公司
        setMultiSelectValue(pushNoticeAppVo.putPlatList, "putPlatList");
        setMultiSelectValue(pushNoticeAppVo.putCompanyTypeList, "putCompanyTypeList");
        setMultiSelectValue(pushNoticeAppVo.putCompanyList, "putCompanyIdList");
        // 回显投放城市
        setMultiSelectValue(pushNoticeAppVo.putProvinceList, "putProvinceIdList");
        setMultiSelectValue(pushNoticeAppVo.putCityList, "putCityIdList");
        setMultiSelectValue(pushNoticeAppVo.putCountyList, "putCountyIdList");
        // 回显工程师分组
        // setMultiSelectValue(pushNoticeAppVo.putEngineerGroupList, "putMasterGroupList");
        // 初始化工程师导入控件
        importExcel(id);
        form.val("zmn-form", pushNoticeApp);
        form.render();
    }

    form.on('submit(zmn-form-submit)', function (obj) {

        obj.field.id = id;
        obj.field.deptOneName = getOptionTextBySelectId("deptOneId");
        obj.field.deptTowName = getOptionTextBySelectId("deptTwoId");
        // 获取所推送的app
        let checkedPutAppsStr = getCheckedPutAppsStr();
        if (zmnUtil.isEmptyNull(checkedPutAppsStr)) {
            layer.msg("必选项不能为空!", {icon: 2});
            return false;
        }

        if (zmnUtil.isEmptyNull(obj.field.picUrl) && obj.field.putType != "3") {
            layer.msg("图片不能为空!", {icon: 2});
            return false;
        }

        if (zmnUtil.isEmptyNull(obj.field.endTime) && obj.field.forLong != "on" && obj.field.putType != "3" ) {
            layer.msg("结束时间不能为空!", {icon: 2});
            return false;
        }

        if (zmnUtil.isEmptyNull(obj.field.userShowTimesAll) && obj.field.isUserShowTimesAll != "on" && obj.field.putType != "3") {
            layer.msg("用户显示总次数不能为空!", {icon: 2});
            return false;
        }

        if (zmnUtil.isEmptyNull(obj.field.userShowTimesDay) && obj.field.isUserShowTimesDay != "on" && obj.field.putType != "3") {
            layer.msg("用户每天显示次数不能为空!", {icon: 2});
            return false;
        }

        obj.field.putAppList = checkedPutAppsStr;
        // 获取需要发布公司得id集合
        let putPlatList = formSelects.value("putPlatList");
        obj.field.putPlatList = formatterItemsToVtDto(putPlatList);
        // 获取公司类型
        let putCompanyTypeList = formSelects.value("putCompanyTypeList");
        obj.field.putCompanyTypeList = formatterItemsToVtDto(putCompanyTypeList);
        // 获取子公司
        let putCompanyList = formSelects.value("putCompanyIdList");
        obj.field.putCompanyList = formatterItemsToVtDto(putCompanyList);
        // 获取省份
        let putProvinceList = formSelects.value("putProvinceIdList");
        obj.field.putProvinceList = formatterItemsToVtDto(putProvinceList);
        // 获取城市
        let putCityList = formSelects.value("putCityIdList");
        obj.field.putCityList = formatterItemsToVtDto(putCityList);
        // 获取区县
        let putCountyList = formSelects.value("putCountyIdList");
        obj.field.putCountyList = formatterItemsToVtDto(putCountyList);
        // 获取工程师分组
        let putEngineerGroupList = formSelects.value("putMasterGroupList");
        obj.field.putEngineerGroupList = formatterItemsToVtDto(putEngineerGroupList);
        let loadingIndex;
        $.ajax({
            type: "POST",
            url: "/push/noticeApp/saveAndEdit.action",
            contentType: "application/json",
            dataType: "json",
            data: JSON.stringify(obj.field),
            beforeSend: function () {
                loadingIndex = layer.load(1, {
                    shade: [0.5, '#DBDBDB'],
                    content: '请稍等...',
                    success: function (layero) {
                        layero.find('.layui-layer-content').css({
                            'padding-top': '40px',//图标与样式会重合，这样设置可以错开
                            'width': '200px',//文字显示的宽度
                            'padding-left': '0px'
                        });
                    }
                });
            },
            error: function () {
                layer.close(loadingIndex);
            },
            success: function (json) {
                layer.close(loadingIndex);
                if (json.status == 200) {
                    layer.msg(json.data, {icon: 1});
                } else {
                    layer.msg(json.message, {icon: 2});
                }
            }
        });
    });

    // 联动二级部门下啦框框
    form.on("select(deptOneId)", function (data) {
        zmnLayUtil.ajaxSimpleUE("/push/noticeApp/loadTwoDeptSelect.action", {pid: data.value}, 0, function (result) {
            let tempHtml = `<option value="">直接选择或搜索选择</option>`;
            $("#deptTwoId").html(tempHtml);
            if (result.status == 200) {
                result.data.forEach(items => {
                    let exAttr = "";
                    let exText = "";
                    tempHtml += '<option value="' + items.value + '" ' + exAttr + '>' + items.text + " " + exText + '</option>';
                });
                $("#deptTwoId").html(tempHtml);
                form.render("select");
            } else {
                layer.msg(result.message, {"icon": 2});
            }
        });
    });

    //省份联动城市 多选
    formSelects.on('putProvinceIdList', function (id, vals, val, isAdd, isDisabled) {
        let provinceIdStr = "";
        if (vals !== null && vals !== undefined && vals.length > 0) {
            vals.forEach(item => {
                provinceIdStr += item.value + ",";
            });
        }
        zmnLayUtil.ajaxSimpleUE("/push/noticeApp/loadCitySelect.action", {pid: provinceIdStr}, 0, function (result) {
            let tempCityHtml = `<option value="">直接选择或搜索选择</option>`;
            $("#putCityId").html(tempCityHtml);
            $("#putCountyId").html(tempCityHtml);
            if (result.status == 200) {
                result.data.forEach(items => {
                    let exAttr = "";
                    let exText = "";
                    tempCityHtml += '<option value="' + items.value + '" ' + exAttr + '>' + items.text + " " + exText + '</option>';
                });
                $("#putCityId").html(tempCityHtml);
                formSelects.render("putCityIdList");
                formSelects.render("putCountyIdList");
            } else {
                layer.msg(result.message, {"icon": 2});
            }
        });
    }, true);

    // 城市联动区县 多选
    formSelects.on('putCityIdList', function (id, vals, val, isAdd, isDisabled) {
        let cityIdStr = "";
        if (vals !== null && vals !== undefined && vals.length > 0) {
            vals.forEach(item => {
                cityIdStr += item.value + ",";
            });
        }
        zmnLayUtil.ajaxSimpleUE("/push/noticeApp/loadCountySelect.action", {pid: cityIdStr}, 0, function (result) {
            let tempCountyHtml = `<option value="">直接选择或搜索选择</option>`;
            $("#putCountyId").html(tempCountyHtml);
            if (result.status == 200) {
                result.data.forEach(items => {
                    let exAttr = "";
                    let exText = "";
                    tempCountyHtml += '<option value="' + items.value + '" ' + exAttr + '>' + items.text + " " + exText + '</option>';
                });
                $("#putCountyId").html(tempCountyHtml);
                formSelects.render("putCountyIdList");
            } else {
                layer.msg(result.message, {"icon": 2});
            }
        });
    }, true);

    // 联动投放公司
    formSelects.on('putCompanyTypeList', function (id, vals, val, isAdd, isDisabled) {

        let types = getSelectAllValue("putCompanyTypeList");
        let plats = getSelectAllValue("putPlatList");
        let obj = {
            types: substr(types),
            plats: substr(plats)
        };
        zmnLayUtil.ajaxSimpleUE("/push/noticeApp/loadCompany.action", obj, 0, function (result) {
            let tempHtml = `<option value="">直接选择或搜索选择</option>`;
            $("#putCompanyId").html(tempHtml);
            if (result.status == 200) {
                result.data.forEach(items => {
                    let exAttr = "";
                    let exText = "";
                    tempHtml += '<option value="' + items.value + '" ' + exAttr + '>' + items.text + " " + exText + '</option>';
                });
                $("#putCompanyId").html(tempHtml);
                formSelects.render("putCompanyIdList");
            }
        });
    }, true);

    form.on("checkbox(forLong)", function (obj) {
        if (obj.elem.checked) {
            form.val("zmn-form", {"endTime": defaultMaxTime});
            disableEme("endTime");
        } else {
            form.val("zmn-form", {"endTime": defaultMinValue});
            enableEme("endTime");
        }
    });

    form.on("checkbox(isUserShowTimesAll)", function (obj) {
        if (obj.elem.checked) {
            form.val("zmn-form", {"userShowTimesAll": defaultMaxNum});
            disableEme("userShowTimesAll");
        } else {
            form.val("zmn-form", {"userShowTimesAll": defaultMinValue});
            enableEme("userShowTimesAll");
        }
    });

    form.on("checkbox(isUserShowTimesDay)", function (obj) {
        if (obj.elem.checked) {
            form.val("zmn-form", {"userShowTimesDay": defaultMaxNum});
            disableEme("userShowTimesDay");
        } else {
            form.val("zmn-form", {"userShowTimesDay": defaultMinValue});
            enableEme("userShowTimesDay");
        }
    });

    form.on("radio(putType)", function (obj) {
        let putType = obj.value;
        switch (putType) {
            case "1":
                loadingPage();
                break;
            case "2":
                homepage();
                break;
            case "3":
                pushMsg();
                break;
        }
        setPicType(putType);
        setBeginTimeType(putType);
        hideByEmeId("picLinkTitle", "picLink");
        form.val("zmn-form", {isJump: "1"});
        form.render();
    });

    form.on("radio(isJump)", function (obj) {
        let isJump = obj.value;
        switch (isJump) {
            case "2":
                showByEmeId("picLinkTitle", "picLink");
                break;
            case "1":
                hideByEmeId("picLinkTitle", "picLink");
                break;
        }
    });

    $(document).on('click', '#stdlib', function () {
        openStdlibPage();
    });

    // 启动页
    function loadingPage() {
        showByEmeId("picTitle", "");
        showByEmeId("showTimeTitle", "showTime");
        showByEmeId("beginTimeTitle", "beginTime");
        showByEmeId("endTimeTitle", "endTime");
        showByEmeId("userShowTimesAllTitle", "userShowTimesAll");
        showByEmeId("userShowTimesDayTitle", "userShowTimesDay");

        hideByEmeId("picLinkTitle", "picLink");
        hideByEmeId("mustReadTitle", "mustRead");
        hideByEmeId("putNameTitle", "putName");
        hideByEmeId("putContentTitle", "putContent");

        let isJump;
        if (zmnUtil.isNull(pushNoticeApp.picLink) || pushNoticeApp.picLink === '') {
            isJump = "1";
            hideByEmeId("picLinkTitle", "picLink");
        } else {
            isJump = "2";
            showByEmeId("picLinkTitle", "picLink");
        }
        form.val("zmn-form", {isJump: isJump});
    }

    // 首页弹框页面隐藏与展示
    function homepage() {
        showByEmeId("picTitle", "");
        showByEmeId("mustReadTitle", "mustRead");
        showByEmeId("userShowTimesAllTitle", "userShowTimesAll");
        showByEmeId("userShowTimesDayTitle", "userShowTimesDay");
        showByEmeId("beginTimeTitle", "beginTime");
        showByEmeId("endTimeTitle", "endTime");

        hideByEmeId("picLinkTitle", "picLink");
        hideByEmeId("putNameTitle", "putName");
        hideByEmeId("putContentTitle", "putContent");
        hideByEmeId("showTimeTitle", "showTime");

        let isJump;
        if (zmnUtil.isNull(pushNoticeApp.picLink) || pushNoticeApp.picLink === '') {
            isJump = "1";
            hideByEmeId("picLinkTitle", "picLink");
        } else {
            isJump = "2";
            showByEmeId("picLinkTitle", "picLink");
        }
        form.val("zmn-form", {isJump: isJump});
    }

    // 推送消息
    function pushMsg() {

        showByEmeId("putNameTitle", "putName");
        showByEmeId("putContentTitle", "putContent");
        showByEmeId("beginTimeTitle", "beginTime");
        hideByEmeId("picTitle", "picUrl");
        hideByEmeId("mustReadTitle", "mustRead");
        hideByEmeId("showTimeTitle", "showTime");
        hideByEmeId("endTimeTitle", "endTime");
        hideByEmeId("userShowTimesAllTitle", "userShowTimesAll");
        hideByEmeId("userShowTimesDayTitle", "userShowTimesDay");

        let isJump;
        if (zmnUtil.isNull(pushNoticeApp.picLink) || pushNoticeApp.picLink === '') {
            isJump = "1";
            hideByEmeId("picLinkTitle", "picLink");
        } else {
            isJump = "2";
            showByEmeId("picLinkTitle", "picLink");
        }
        form.val("zmn-form", {isJump: isJump});
    }

    function showByEmeId(emeId, valueEmeId) {
        if (isShow(emeId)) {
            $("#" + emeId).show();
            $('#' + valueEmeId).attr('lay-verify', 'required');
            $("#" + valueEmeId).val("");
        }
    }

    function hideByEmeId(emeId, valueEmeId) {
        if (!isShow(emeId)) {
            $("#" + emeId).hide();
            if (!zmnUtil.isNull(valueEmeId)) {
                $('#' + valueEmeId).attr('lay-verify', '');
                $('#' + valueEmeId).val("");
            }
        }
    }

    function isShow(emeId) {
        return $("#" + emeId).is(":hidden");
    }

    function initLayDataByEmeId(emeId) {
        laydate.render({
            elem: '#' + emeId,
            type: 'datetime',
            format: "yyyy-MM-dd HH:mm:ss"
        });
    }

    function disableEme(emeIds) {
        $("#" + emeIds).attr("disabled", true);
        $("#" + emeIds).attr("class", "layui-input layui-disabled");
    }

    function enableEme(emeIds) {
        $("#" + emeIds).attr("disabled", false);
        $("#" + emeIds).attr("class", "layui-input");
    }

    function getOptionTextBySelectId(emeId) {
        let options = $("#" + emeId + " option:selected");
        return options.text();
    }

    function getCheckedPutAppsStr() {
        let arr = [];
        $("input:checkbox[name='app']:checked").each(function (i) {
            let map = {};
            map.value = $(this).val();
            map.text = $(this).val();
            arr.push(map);
        });
        return arr;
    }

    function openStdlibPage() {
        layer.open({
            type: 2,
            title: "标准库选择",
            area: ['60%', '60%'],
            content: "/push/noticeApp/stdlibPage.action"
        });
    }

    function getSelectAllValue(emeId) {
        return formSelects.value(emeId, 'val');
    }

    function formatterItemsToVtDto(items) {
        let arr = [];
        items.forEach(item => {
            let map = {};
            map.value = item.value;
            map.text = item.name;
            arr.push(map);
        });
        return arr;
    }

    function substr(val) {
        let str = "";
        if (val !== null && val !== undefined && val.length > 0) {
            val.forEach(item => {
                str += item + ",";
            });
        }
        return str;
    }

    function setMultiSelectValue(items, emeId) {
        let arr = [];
        items.forEach(item => {
            arr.push(item.value);
        });
        formSelects.value(emeId, arr);
    }

    function setCheckboxData(items) {
        $("input:checkbox[name='app']").each(function (i) {
            items.forEach(item => {
                if ($(this).val() == item.value) {
                    $(this).prop("checked", true);
                }
            });
        });
    }

    function setEndTime(val) {
        if (val == "9999-12-31 23:59:59") {
            $("#forLong").prop("checked", true);
            form.val("zmn-form", {"endTime": defaultMaxTime});
            disableEme("endTime");
        } else {
            $("#forLong").prop("checked", false);
            form.val("zmn-form", {"endTime": defaultMinValue});
            enableEme("endTime");
        }
    }

    function setIsUserShowTimesAll(val) {
        if (val == defaultMaxNum) {
            $("#isUserShowTimesAll").prop("checked", true);
            form.val("zmn-form", {"userShowTimesAll": defaultMaxNum});
            disableEme("userShowTimesAll");
        } else {
            $("#isUserShowTimesAll").prop("checked", false);
            form.val("zmn-form", {"userShowTimesDay": defaultMinValue});
            enableEme("userShowTimesAll");
        }
    }

    function setIsUserShowTimesDay(val) {
        if (val == defaultMaxNum) {
            $("#isUserShowTimesDay").prop("checked", true);
            form.val("zmn-form", {"userShowTimesDay": defaultMaxNum});
            disableEme("userShowTimesDay");
        } else {
            $("#isUserShowTimesDay").prop("checked", false);
            form.val("zmn-form", {"userShowTimesDay": defaultMinValue});
            enableEme("userShowTimesDay");
        }
    }

    function setPicType(putType) {
        if (zmnUtil.isNull(putType)) {
            $("#picTitleLabel").html("弹框图片：<span style=\"color: red\">*</span>");
            $("#picTitleP").html("点击上传，弹框图片");
            $("#picLabelMid").html("(宽610px / 高度不限（最佳尺寸610x580)，大小不超过5M)");
        }
        if (putType == "2") {
            $("#picTitleLabel").html("弹框图片：<span style=\"color: red\">*</span>");
            $("#picTitleP").html("点击上传，弹框图片");
            $("#picLabelMid").html("(宽610px / 高度不限（最佳尺寸610x580)，大小不超过5M)");
        }
        if (putType == "1") {
            $("#picTitleLabel").html("宣传图片：<span style=\"color: red\">*</span>");
            $("#picTitleP").html("点击上传，宣传图片");
            $("#picLabelMid").html("宽1242px/高度2208（安全区域1020x1972)，大小不超过5M");
        }
    }

    function setBeginTimeType(type) {
        if (type == '3') {
            $("#beginTimeName").html("推送时间：<span style=\"color: red\">*</span>");
        } else {
            $("#beginTimeName").html("开始时间：<span style=\"color: red\">*</span>");
        }
    }

    window.pushNoticeDetailPage = {
        getSonPageValueSetUrl: function (val) {
            let baseUrl = "https://plat.xiujiadian.com/standard/record/preview.action?standardId=" + val;
            form.val("zmn-form", {picLink: baseUrl});
        }
    };

    $(document).on('click', '.show_big_image', function () {
        $(this).prevAll().each(function (index, val) {
            if (val.localName === "div") {
                $(val).find("input[type='hidden']").each(function (i, v) {
                    let src = $(v).val();
                    if (!zmnUtil.isNull(src)) {
                        zmnUploadUtil.showBigImg(src);
                        return true;
                    }
                });
            }
        });
    });

    $(document).on('click', '.delete_image', function () {
        $(this).prevAll().each(function (index, val) {
            if (val.localName === "div") {
                val.removeAttribute('style');
                Array.from(val.children).forEach(function (item) {
                    item.removeAttribute('style');
                });
                val.removeAttribute('value');
            }
            $(val).find("input[type='hidden']").each(function (i, v) {
                $(v).attr("value", "");
            });
        });
    });

    $(document).on('click', '#outPutTemplate', function () {
        let index = layer.load(1, {
            shade: [0.5, '#DBDBDB']
        });
        zmnUtil.download("/push/noticeApp/outPutTemplate.action", "投放工程师模板.xlsx", function () {
            layer.close(index);
        });
    });

    function importExcel(noticeId) {
        let loadingExcel;
        upload.render({
            elem: '#importExcel'
            , multiple: true
            , accept: 'file'
            , exts: "xlsx|xls"
            , url: "/push/noticeApp/importExcel.action?noticeId=" + noticeId
            , before: function (obj) {
                loadingExcel = layui.layer.load(1, {
                    shade: [0.5, '#DBDBDB']
                });
            }
            , done: function (res) {
                if (res.status == 200) {
                    layer.msg(res.data, {icon: 1});
                } else {
                    layer.msg(res.message, {icon: 2});
                }
                layui.layer.close(loadingExcel);
            }
            , error: function (resErr) {
                layui.layer.close(loadingExcel);
            }
        });
    }

    $(document).on('click', '.info-form-cancel', function () {
        parent.layui.admin.events.closeThisTabs();
    });

    //对外暴露的接口
    exports('push_notice_detail', {});
})
;

